package com.wenwen.social.application.impl;

import com.wenwen.social.application.FileApplication;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Stack;

import static com.sun.deploy.cache.Cache.exists;
import static com.wenwen.social.constant.FileConstant.IMG_TYPE;
import static com.wenwen.social.constant.FileConstant.VIDEO_TYPE;
import static org.apache.commons.lang.SystemUtils.FILE_SEPARATOR;


@Service
@Slf4j
public class FileApplicationImpl implements FileApplication {

	@Value("${FileBasePath}")
	private String fileBasePath;
	@Value("${VideoPath}")
	private String videoPath;
	@Value("${ImagePath}")
	private String imagePath;

	@Override
	public String upload(MultipartFile file,int type,Long uid) {
		if(file.isEmpty()){
			log.info("没有选择文件");
			return "";
		}

		String fileName = file.getOriginalFilename();
		String basePath = fileBasePath ;
		String path = getParentPathByType(type);
		if("".equals(path)) return "";
		String prePath = basePath+FILE_SEPARATOR+uid+FILE_SEPARATOR+path+FILE_SEPARATOR;
		File dest = new File(prePath + fileName);
		//先进后出
		Stack<File> stack = new Stack();
		File parentFile = dest.getParentFile();
		while(!parentFile.exists()){
			stack.push(parentFile);
			parentFile=parentFile.getParentFile();
		}
		while (!stack.empty()){
			File addParentFile = stack.pop();
			addParentFile.mkdir();
		}

		try {
			file.transferTo(dest); //保存文件
			return dest.getPath();
		} catch (IllegalStateException e) {
			log.error("上传文件异常：{}",uid+",file:"+file.getOriginalFilename(),e);
			return "";
		} catch (IOException e) {
			log.error("上传文件IO异常：{}",uid+",file:"+file.getOriginalFilename(),e);
			return "";
		}
	}

	private String getParentPathByType(int type) {
		if(type == IMG_TYPE) return imagePath;
		if(type == VIDEO_TYPE) return videoPath;
		return "";
	}

	@Override
	public HttpServletResponse downLoad(HttpServletResponse response,int type,Long uid,String filename){
		String path = getParentPathByType(type);

		if("".equals(path)){
			response.setStatus(500);
			log.info("未传入下载文件类型参数:type={},uid={}",type,uid);
			return response;
		}
		File file = new File(fileBasePath+FILE_SEPARATOR+uid + FILE_SEPARATOR+path+FILE_SEPARATOR + filename);
		if(file.exists()){ //判断文件父目录是否存在
			response.setContentType("application/force-download");
			response.setHeader("Content-Disposition", "attachment;fileName=" + filename);

			byte[] buffer = new byte[1024];
			FileInputStream fis = null; //文件输入流
			BufferedInputStream bis = null;
			OutputStream os = null; //输出流
			try{
				os = response.getOutputStream();
				fis = new FileInputStream(file);
				bis = new BufferedInputStream(fis);
				int i = bis.read(buffer);
				while(i != -1){
					os.write(buffer);
					i = bis.read(buffer);
				}
			}catch (Exception e) {
				// TODO Auto-generated catch block
				log.error("下载文件异常：filename:{},uid:{}",filename,uid,e);
			}finally {
				try {
					if(bis != null)	bis.close();
					if(fis != null) fis.close();
				} catch (IOException e) {
					log.error("下载文件异常：filename:{},uid:{}",filename,uid,e);
				}
			}
		}
		return response;
	}
}
